<?php

namespace App\Http\Controllers\ChinaBank\Admin;

use App\Models\ChinaBank\ShopAddressModel;
use App\Models\ChinaBank\ShopModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ShopController extends Controller
{
    public function brands(Request $request){
        $brands = ShopModel::get();

        return self::adminview("shop/brand-list",["brands"=>$brands]);
    }

    public function brand_edit(Request $request){

        $id = $request->input('id',0);
        if($request->method() == 'POST')
        {
            $name = trim($request->input('name',''));
            if($id > 0){

                ShopModel::update(['id'=>$id,'name'=>$name]);
                return self::send();
            }else{

                if(ShopModel::where('name',$name)->first())
                {
                    return self::send(201,"名字重复");
                }
                ShopModel::create(['name'=>$name]);
                return self::send();
            }
        }

        if($id > 0){
            $brand = ShopModel::find($id);
        }else{
            $brand = new \stdClass();
            $brand->id = 0;
            $brand->name= "";
        }

        return self::adminview("shop/brand-edit",['brand'=>$brand]);
    }

    public function brand_del(Request $request){
        $id = $request->input('id');
        ShopModel::where('id',$id)->delete();
        return self::send();
    }


    public function brand_shops(Request $request)
    {
        $brandId = $request->input('id');

        $shops  = ShopAddressModel::where('shop',$brandId)->get();

        return self::adminview("shop/shop-list",['shops'=>$shops,'brandId'=>$brandId]);
    }


    public function shop_del(Request $request){
        ShopAddressModel::where('id',$request->input('id'))->delete();
        return self::send();
    }

    public function shop_edit(Request $request){
        $id     = $request->input('id',0);

        if($request->method() == 'POST'){
            $data = $request->all(["name","detail","lat","lon","shop"]);
            if($id > 0){
                ShopAddressModel::where('id',$id)->update($data);
            }else{
                ShopAddressModel::create($data);
            }
            return self::send();
        }


        if($id == 0){
            $shop   = new \stdClass();
            $shop->id = 0;
            $shop->name = "";
            $shop->detail = "";
            $shop->lat = "";
            $shop->lon = "";
            $shop->shop = $request->input('shop');
        }else{

            $shop = ShopAddressModel::find($id);
        }
        return self::adminview("shop/shop-edit",['shop'=>$shop]);
    }
}
